package org.finesys.boot.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.finesys.common.core.exception.ErrorCodes;
import org.finesys.common.core.module.R;
import org.finesys.common.core.util.MessageUtil;
import org.finesys.system.api.dto.SysUserDTO;
import org.finesys.system.api.dto.UserGiteeDto;
import org.finesys.system.api.dto.UserInfo;
import org.finesys.system.api.entity.SysUser;
import org.finesys.system.api.entity.SysUserGitee;
import org.finesys.system.api.service.UserGiteeService;
import org.finesys.system.service.SysUserService;
import org.finesys.system.service.SysUsersGiteeService;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

@Service
@RequiredArgsConstructor
public class UserGiteeServiceImpl implements UserGiteeService {
    private final SysUsersGiteeService sysUsersGiteeService;
    private final SysUserService sysUserService;

    /**
     * 添加
     */
    public R<Boolean> add(@RequestBody UserGiteeDto userGiteeDto) {
        return R.success(sysUsersGiteeService.addSysUsersGitee(userGiteeDto));
    }

    /**
     * 更新
     */
    public R<Boolean> update(@RequestBody UserGiteeDto userGiteeDto) {
        return R.success(sysUsersGiteeService.update(userGiteeDto));
    }

    /**
     * 绑定
     */
    public R<Boolean> binding(@RequestBody UserGiteeDto userGiteeDto) {
        return R.success(sysUsersGiteeService.binding(userGiteeDto));
    }

    /***
     * 根据AppId、id查询
     */
    public R<UserGiteeDto> getByAppIdAndId(@RequestParam("appId") String appId, @RequestParam(value = "id") Long id) {
        return R.success(sysUsersGiteeService.getByAppidAndId(appId, id.intValue()));
    }

    /**
     * 获取绑定用户信息
     */
    public R<SysUserDTO> getUser(@RequestParam(value = "appId") String appId, @RequestParam(value = "id") Long id) {
        return R.success(sysUsersGiteeService.getUser(appId, id.intValue()));
    }

    /**
     * 通过用户名查找用户信息
     *
     * @param userGiteeDto 用户信息
     * @return 用户信息
     */
    public R<UserInfo> info(UserGiteeDto userGiteeDto) {
        String appId = userGiteeDto.getAppId();
        SysUserGitee sysUserGitee = sysUsersGiteeService.getOne(Wrappers.<SysUserGitee>query()
                .lambda()
                .eq(StrUtil.isNotBlank(appId), SysUserGitee::getAppId, appId));

        if (sysUserGitee == null) {
            return R.failed(MessageUtil.getMessage(ErrorCodes.SYS_USER_GITEE_USERINFO_EMPTY, appId));
        }
        SysUser user = sysUserService.getById(sysUserGitee.getUserId());
        if (user == null) {
            return R.failed(MessageUtil.getMessage(ErrorCodes.SYS_USER_USERINFO_EMPTY, appId));
        }
        return R.success(sysUserService.getUserInfo(user));
    }
}
